
// 1 弹出和关闭 模态框 （2种方式）
// 1 通过给标签增加属性即可 
// - 1 显示 data-bs-toggle="modal" data-bs-target="#addModal" 和 真实的模态框div的id 联系 
// - 2 隐藏 data-bs-dismiss="modal"
// 2 通过 调用js代码来实现
// - 1 $("模态框的选择器").modal("show")
// - 2 $("模态框的选择器").modal("hide")

// 获取dom元素
const tbody = document.querySelector('tbody');
const province = document.querySelector('select[name=province]');
const city = document.querySelector('select[name=city]');
const county = document.querySelector('select[name=county]');

const form = document.querySelector('.add-form');
const create = document.querySelector('.create');
const modalTitle = document.querySelector('#addModalLabel');

// let id;

// 获取学生数据
async function getStudentList() {
  const res = await axios({
    url: '/student/list',
  })
  // console.log(res.data.data);
  const studentData = res.data.data;
  tbody.innerHTML = studentData.map(item => {
    const { id, name, age, sex, group, phone, salary, truesalary, province, city, county } = item;
    return `
        <tr>
          <th scope="row">${id}</th>
          <td>${name}</td>
          <td>${age}</td>
          <td>${sex}</td>
          <td>${group}</td>
          <td>${phone}</td>
          <td>${salary}</td>
          <td>${truesalary}</td>
          <td>${province + city + county}</td>
          <td>
            <button type="button" class="btn btn-primary btn-sm update" data-id=${id}>修改</button>
            <button type="button" class="btn btn-danger btn-sm delete" data-id=${id}>删除</button>
          </td>
        </tr>
        `
  }).join('');
}

// 获取省份数据
async function getProvince() {
  // #region 原功能
  /*
  const res = await axios({
    url: '/geo/province',
  })
  // console.log(res.data); // 验证信息是否成功获取
  province.innerHTML = res.data.reduce((beforeHTML, item) => {
    return beforeHTML + `<option value="${item}">${item}</option>`
  }, '<option selected value="">--省--</option>')
  */
  // #endregion
  getData('/geo/province', {}, '省', province);
}

getStudentList()
getProvince()

// 省发生变化
province.addEventListener('change', async () => {
  // #region 原功能
  /*
  const res = await axios({
    url: '/geo/city',
    params: {
      pname: province.value,
    }
  })
  // console.log(res.data); // 验证信息是否成功获取
  city.innerHTML = res.data.reduce((beforeHTML, item) => {
    return beforeHTML + `<option value="${item}">${item}</option>`
  }, '<option selected value="">--市--</option>')
  */
  // #endregion
  getData('/geo/city', { pname: province.value, }, '市', city);
  // county.innerHTML = '<option selected value="">--县--</option>'
  county.innerHTML = county.firstChild.outerHTML; // 和上一条效果一致
})

// 市发生变化
city.addEventListener('change', async () => {
  // #region 原功能
  /*
  const res = await axios({
    url: '/geo/county',
    params: {
      pname: province.value,
      cname: city.value
    }
  })
  // console.log(res.data); // 验证信息是否成功获取
  county.innerHTML = res.data.reduce((beforeHTML, item) => {
    return beforeHTML + `<option value="${item}">${item}</option>`
  }, '<option selected value="">--县--</option>')
  */
  // #endregion
  getData('/geo/county',
    {
      pname: province.value,
      cname: city.value
    },
    '县', county);
})

// 优化封装
async function getData(url, params, text, target) {
  const res = await axios({
    url,
    params
  })
  // console.log(res.data); // 验证信息是否成功获取
  target.innerHTML = res.data.reduce((beforeHTML, item) => {
    return beforeHTML + `<option value="${item}">${item}</option>`
  }, `<option selected value="">--${text}--</option>`)
}

// 提交
form.addEventListener('submit', async e => {
  e.preventDefault();
  const data = serialize(form, { hash: true, empty: true }) // empty 可以使 serialize 获取表单空值
  // console.log(data); // 测试捕获是否成功

  const formTitle = document.querySelector('#addModalLabel')

  if (formTitle.innerText === '录入新学员') {
    delete data.id;
  }

  for (const key in data) {
    if (!data[key]) {
      toastr.warning('我超，填写完整信息', '提醒')
      return;
    }
  }

  let res;

  if (formTitle.innerText === '录入新学员') {
    res = await axios({
      url: '/student/add',
      method: 'post',
      data
    })
    console.log(res); // 测试新增是否成功
    getStudentList() // 再次渲染页面
    $('#addModal').modal('hide'); // 关闭模态框
    form.reset(); // 重置输入框、单选框
    city.innerHTML = city.firstChild.outerHTML; // 重置市级下拉框
    county.innerHTML = county.firstChild.outerHTML;  // 重置县级下拉框

  } else if (formTitle.innerText = '修改学员信息') {
    // data.id = id;
    res = await axios({
      url: '/student/update',
      method: 'put',
      data
    })
    console.log(res); // 测试修改是否成功

    if (res.data.code === 0) {
      toastr.success(res.data.message, "恭喜");
      $("#addModal").modal("hide");
      getStudentList() // 再次渲染页面
      form.reset();
      city.innerHTML = city.firstChild.outerHTML;
      county.innerHTML = county.firstChild.outerHTML;
    }
  }
})

//点击编辑按钮，事件委托
tbody.addEventListener('click', async (e) => {
  const target = e.target;
  if (target.classList.contains('update')) {
    // console.log('点击修改触发');
    let id = +target.dataset.id;
    modalTitle.innerText = '修改学员信息';
    $('#addModal').modal('show'); // 模态框弹出
    const res = await axios({
      url: '/student/one',
      params: {
        id
      }
    })
    // console.log(res.data.data); // 验证是否获取成功
    const studentObj = res.data.data; // 拿到学生数据（对象）
    await getData('/geo/city', { pname: studentObj.province, }, '市', city);
    // 渲染下拉框内容
    await getData('/geo/county',
      {
        pname: studentObj.province,
        cname: studentObj.city
      },
      '县', county);
    // 渲染下拉框内容

    for (const key in studentObj) {
      let studentInfo = document.querySelector(`[name=${key}]`);
      if (studentInfo && key !== 'sex') {
        studentInfo.value = studentObj[key];
      }
    }
    document.querySelector(`[name=sex][value=${studentObj.sex}]`).checked = true;
  }

  if (target.classList.contains('delete')) {
    let id = +target.dataset.id;
    if (confirm("你确定要进行删除吗？")) {
      const res = await axios({
        url: 'student/delete',
        method: 'delete',
        params: {
          id
        }
      })
      if (res.data.code === 0) {
        toastr.success("真的删除了啦", "哇靠");
        getStudentList();
      }
    }
  }
})

// 点击新增模态框弹出
create.addEventListener('click', () => {
  modalTitle.innerText = '录入新学员';
  $('#addModal').modal('show');
  form.reset(); // 重置输入框、单选框
  city.innerHTML = city.firstChild.outerHTML; // 重置市级下拉框
  county.innerHTML = county.firstChild.outerHTML;  // 重置县级下拉框
})